#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
Attributes:
    __version__ (str): "0.0.1"
    __copyright__ (str): "Copyright (C) 2025 z"
    __license__ (str): "MIT"
    __author__ (str): "Z"
"""

import re

from wingman import logger
from wingman.common.error import ErrorCode
from config.rules_filter import *
from config.rules_target import *
from config.system import (
    IS_DINGTALK_SEND, IS_FEISHU_SEND, IS_SLACK_SEND,
    DINGTALK_DEV_TOKEN, DINGTALK_TEST_TOKEN, DINGTALK_PRE_TOKEN, DINGTALK_PROD_TOKEN, DINGTALK_DEBUG_TOKEN,
    SLACK_DEV_CHANNEL, SLACK_TEST_CHANNEL, SLACK_PRE_CHANNEL, SLACK_PROD_CHANNEL, SLACK_DEBUG_CHANNEL,
    FEISHU_DEV_ACCESS, FEISHU_TEST_ACCESS, FEISHU_PRE_ACCESS, FEISHU_PROD_ACCESS, FEISHU_DEBUG_ACCESS,
)


class TalkMap:
    """消息内容分发"""

    def __get_filtered(self, message, function_name):
        # 检查是否包含需要过滤的内容
        is_filtered = False
        filter_rules = globals()[function_name + "_filtered_keys"]
        # filter_rules = globals().get(function_name + "_filtered_keys", {"title": "debug", "customize_env": "debug", "message": message})

        for rule in filter_rules:
            pattern = re.compile(rule)  # 将规则编译为正则表达式
            for key, value in message.items():
                if pattern.search(str(value)):  # 使用search方法进行匹配
                    is_filtered = True
                    break
            if is_filtered:
                break

        return is_filtered

    def __check_env(self, value):
        for env in ["dev", "test", "pre", "prod", "debug"]:
            if env in value:
                return env
        return "debug"

    def __get_env_name(self, env_name):
        credentials = {
            "dev": (DINGTALK_DEV_TOKEN, SLACK_DEV_CHANNEL, FEISHU_DEV_ACCESS),
            "test": (DINGTALK_TEST_TOKEN, SLACK_TEST_CHANNEL, FEISHU_TEST_ACCESS),
            "pre": (DINGTALK_PRE_TOKEN, SLACK_PRE_CHANNEL, FEISHU_PRE_ACCESS),
            "prod": (DINGTALK_PROD_TOKEN, SLACK_PROD_CHANNEL, FEISHU_PROD_ACCESS),
            "debug": (DINGTALK_DEBUG_TOKEN, SLACK_DEBUG_CHANNEL, FEISHU_DEBUG_ACCESS)
        }
        if env_name in credentials:
            self.dingtalk_token, self.slack_channel, self.feishu_access = credentials[env_name]
        else:
            self.dingtalk_token, self.slack_channel, self.feishu_access = credentials["debug"]

    def __target_content(self, message, function_name):
        # 定义需要筛选的键
        message_keys = globals()[function_name + "_message_keys"]
        title_keys = globals()[function_name + "_title_keys"]
        # message_keys = globals().get(function_name + "_message_keys", {"title": "debug", "customize_env": "debug", "message": message})
        # title_keys = globals().get(function_name + "_title_keys", {"title": "debug"})

        # result_message = ""
        result_message = {}
        result_title = ""
        result_env_name = ""

        for key, value in message.items():
            if key in message_keys:
                # result_message += f"{key} :  {value}\n"
                result_message.update({f"{key}": f"{value}"})
            if key in title_keys:
                result_title += f"{value}"
            if key in "customize_env":
                result_env_name = self.__check_env(value)
        return result_title, result_message, result_env_name

    def get_send(self, message, function_name):
        """根据标志判断是否发送"""
        if self.__get_filtered(message, function_name):
            logger.warning(ErrorCode.GETSEND.value, "send Message contains filtered content, will not send.", __name__)
        else:
            if IS_DINGTALK_SEND:
                from wingman import ding
                title, content, env_name = self.__target_content(message, function_name)
                self.__get_env_name(env_name)
                try:
                    ding.get_send(token=self.dingtalk_token, title=title, message=content)
                except Exception as e:
                    logger.error(ErrorCode.CALLSEND_GETSEND_DING.value, str(e), __name__)
            if IS_FEISHU_SEND:
                from wingman import feishu
                title, content, env_name = self.__target_content(message, function_name)
                self.__get_env_name(env_name)
                try:
                    feishu.get_send(access=self.feishu_access, title=title, message=content)
                except Exception as e:
                    logger.error(ErrorCode.CALLSEND_GETSEND_FEISHU.value, str(e), __name__)
            if IS_SLACK_SEND:
                from wingman import slack
                title, content, env_name = self.__target_content(message, function_name)
                self.__get_env_name(env_name)
                try:
                    slack.get_send(channel=self.slack_channel, title=title, text=content)
                except Exception as e:
                    logger.error(ErrorCode.CALLSEND_GETSEND_SLACK.value, str(e), __name__)
